﻿using GBT.SystemEnties;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Attribute = GBT.SystemEnties.Attribute;

namespace GBT.SystemBusinessCore
{
    public class DbContext<T> where T : class, new()
    {
        public DbContext(string DBName)
        {
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = "server=ip/hostname;uid=sa;pwd=xxxx;database=" + DBName,
                DbType = DbType.SqlServer,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
                IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了

            });
            //调式代码 用来打印SQL 
            Db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql + "\r\n" +
                    Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };

        }
        //注意：不能写成静态的
        public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作
        public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } }//用来操作当前表的数据

        public SimpleClient<Attribute> AttributeDb { get { return new SimpleClient<Attribute>(Db); } }//用来处理Attribute表的常用操作
        public SimpleClient<UserRole> UserRoleDb { get { return new SimpleClient<UserRole>(Db); } }//用来处理UserRole表的常用操作
        public SimpleClient<UserPrivilege> UserPrivilegeDb { get { return new SimpleClient<UserPrivilege>(Db); } }//用来处理UserPrivilege表的常用操作
        public SimpleClient<Dishes> DishesDb { get { return new SimpleClient<Dishes>(Db); } }//用来处理Dishes表的常用操作
        public SimpleClient<DishesClass> DishesClassDb { get { return new SimpleClient<DishesClass>(Db); } }//用来处理DishesClass表的常用操作
        public SimpleClient<DishesAttribute> DishesAttributeDb { get { return new SimpleClient<DishesAttribute>(Db); } }//用来处理DishesAttribute表的常用操作
        public SimpleClient<UserDishes> UserDishesDb { get { return new SimpleClient<UserDishes>(Db); } }//用来处理UserDishes表的常用操作
        public SimpleClient<TakeFoodRecord> TakeFoodRecordDb { get { return new SimpleClient<TakeFoodRecord>(Db); } }//用来处理TakeFoodRecord表的常用操作
        public SimpleClient<Announcement> AnnouncementDb { get { return new SimpleClient<Announcement>(Db); } }//用来处理Announcement表的常用操作
        public SimpleClient<AddressBook> AddressBookDb { get { return new SimpleClient<AddressBook>(Db); } }//用来处理AddressBook表的常用操作
        public SimpleClient<ReportMeals> ReportMealsDb { get { return new SimpleClient<ReportMeals>(Db); } }//用来处理ReportMeals表的常用操作
        public SimpleClient<EvaluationResult> EvaluationResultDb { get { return new SimpleClient<EvaluationResult>(Db); } }//用来处理EvaluationResult表的常用操作
        public SimpleClient<IncrementalMeal> IncrementalMealDb { get { return new SimpleClient<IncrementalMeal>(Db); } }//用来处理IncrementalMeal表的常用操作
        public SimpleClient<DiningHall> DiningHallDb { get { return new SimpleClient<DiningHall>(Db); } }//用来处理DiningHall表的常用操作
        public SimpleClient<EvaluationContentToResult> EvaluationContentToResultDb { get { return new SimpleClient<EvaluationContentToResult>(Db); } }//用来处理EvaluationContentToResult表的常用操作
        public SimpleClient<MealTime> MealTimeDb { get { return new SimpleClient<MealTime>(Db); } }//用来处理MealTime表的常用操作
        public SimpleClient<EvaluationContent> EvaluationContentDb { get { return new SimpleClient<EvaluationContent>(Db); } }//用来处理EvaluationContent表的常用操作
        public SimpleClient<MealUser> MealUserDb { get { return new SimpleClient<MealUser>(Db); } }//用来处理MealUser表的常用操作
        public SimpleClient<EvaluationUser> EvaluationUserDb { get { return new SimpleClient<EvaluationUser>(Db); } }//用来处理EvaluationUser表的常用操作
        public SimpleClient<EvaluationIdea> EvaluationIdeaDb { get { return new SimpleClient<EvaluationIdea>(Db); } }//用来处理EvaluationIdea表的常用操作


        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetList()
        {
            return CurrentDb.GetList();
        }

        /// <summary>
        /// 根据表达式查询
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetList(Expression<Func<T, bool>> whereExpression)
        {
            return CurrentDb.GetList(whereExpression);
        }


        /// <summary>
        /// 根据表达式查询分页
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel pageModel)
        {
            return CurrentDb.GetPageList(whereExpression, pageModel);
        }

        /// <summary>
        /// 根据表达式查询分页并排序
        /// </summary>
        /// <param name="whereExpression">it</param>
        /// <param name="pageModel"></param>
        /// <param name="orderByExpression">it=>it.id或者it=>new{it.id,it.name}</param>
        /// <param name="orderByType">OrderByType.Desc</param>
        /// <returns></returns>
        public virtual List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel pageModel, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
        {
            return CurrentDb.GetPageList(whereExpression, pageModel, orderByExpression, orderByType);
        }


        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <returns></returns>
        public virtual T GetById(dynamic id)
        {
            return CurrentDb.GetById(id);
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(dynamic id)
        {
            return CurrentDb.Delete(id);
        }


        /// <summary>
        /// 根据实体删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(T data)
        {
            return CurrentDb.Delete(data);
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(dynamic[] ids)
        {
            return CurrentDb.AsDeleteable().In(ids).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 根据表达式删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(Expression<Func<T, bool>> whereExpression)
        {
            return CurrentDb.Delete(whereExpression);
        }


        /// <summary>
        /// 根据实体更新，实体需要有主键
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Update(T obj)
        {
            return CurrentDb.Update(obj);
        }

        /// <summary>
        ///批量更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Update(List<T> objs)
        {
            return CurrentDb.UpdateRange(objs);
        }

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Insert(T obj)
        {
            return CurrentDb.Insert(obj);
        }


        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Insert(List<T> objs)
        {
            return CurrentDb.InsertRange(objs);
        }


        //自已扩展更多方法 

        /// <summary>
        /// 插入并返回实体
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual T InsertReturnEntity(T obj)
        {
            return Db.Insertable(obj).ExecuteReturnEntity();
        }

        /// <summary>
        /// 插入并返回受影响的行数
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual int InsertReturnLineNumber(T obj)
        {
            return Db.Insertable(obj).ExecuteCommand();
        }

        /// <summary>
        /// 插入并返回自增列(ID)的值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual int InsertReturnIdentity(T obj)
        {
            return Db.Insertable(obj).ExecuteReturnIdentity();
        }

        /// <summary>
        /// 更新并返回受影响的行数
        /// </summary>
        /// <param name="obj">实体中必须包含主键</param>
        /// <returns></returns>
        public virtual int UpdateReturnLineNumber(T obj)
        {
            return Db.Updateable(obj).ExecuteCommand();
        }

        /// <summary>
        /// 批量更新并返回受影响的行数
        /// </summary>
        /// <param name="listObj">实体列表，每个列表项中必须包含主键</param>
        /// <returns></returns>
        public virtual int UpdateReturnLineNumber(List<T> listObj)
        {
            return Db.Updateable(listObj).ExecuteCommand();
        }

        /// <summary>
        /// 根据指定的条件更新并返回受影响的行数
        /// </summary>
        /// <param name="obj">实体</param>
        /// <param name="expressionWhere">条件拉姆达</param>
        /// <returns></returns>
        public virtual int Update(T obj, Expression<Func<T, bool>> expressionWhere)
        {
            return Db.Updateable(obj).Where(expressionWhere).ExecuteCommand();
        }

        /// <summary>
        /// 更新返回实体
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual T UpdateReturnEntity(T obj)
        {
            return Db.Saveable(obj).ExecuteReturnEntity();
        }

        public virtual bool IsExists(Expression<Func<T, bool>> whereLambda)
        {
            List<T> list = Db.Queryable<T>().Where(whereLambda).ToList();
            if (list.Count > 0)
            {
                return true;
            }
            return false;
        }
    }
}

